/**
 * Copyright (C), 2015-2019, 静修教育咨询有限公司
 * FileName: ChitchatController
 * Author:  SAGIRI
 * Date:     2019/7/24 0024 11:16
 * Description: 教师与家长聊天控制器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.ruimei.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.ruimei.entitys.*;
import com.ruimei.mapper.UserMapper;
import com.ruimei.service.IChitchatService;
import com.ruimei.util.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 〈概要〉<br> 
 * 〈教师与家长聊天控制器〉
 *
 * @author SAGIRI
 * @create 2019/7/24 0024
 * @since 1.0.0
 */
@RestController
@Api(tags = "聊天回复控制器")
public class ChitchatController {

    @Resource
    private IChitchatService chitchatService ;
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private UserMapper userMapper;

    /**
     *
     * @param request
     * @param studentList 学生参数对象 正文传递
     * @param content 内容
     * @return
     */
    @PostMapping(value = "/sendMessage")
    @ApiOperation(value = "教师发送消息至家长")
    public JSONObject sendMessage(HttpServletRequest request,String studentList,String content){
        List<ParentAndStudent> list = JSON.parseArray(studentList,ParentAndStudent.class);
        String id = TokenUtils.getTeacherId(request);
       Teacher teacher =  JSON.parseObject(redisTemplate.opsForValue().get(id), Teacher.class);
        return  chitchatService.sendMessage(list,teacher.getFullName(), content,id);
    }

    /**
     *
     * @param request
     * @param teacherList 老师id数组
     * @param content 内容
     * @param studentName 学生姓名
     * @param studentId 学生id
     * @return
     */
    @PostMapping(value = "/sendMessageToTeacher")
    @ApiOperation(value = "家长发送消息至老师")
    public JSONObject sendMessageToTeacher(HttpServletRequest request,String teacherList,String content,
                                           String studentName,String studentId){
        List<String> list = JSON.parseArray(teacherList,String.class);
        String id =  TokenUtils.getParentId(request);
        Parent parent = JSON.parseObject(redisTemplate.opsForValue().get(id),Parent.class);
            return  chitchatService.sendMessageToTeacher(list,parent.getFullName(), content,studentName,studentId,parent.getId());
        }

    /**
     *
     * @param request
     * @param type 类型
     * @param studentId 学生id
     * @return
     */
    @PostMapping(value = "/queryMessageTitle")
    @ApiOperation(value = "显示消息标题列表")
    public JSONObject queryMessage(HttpServletRequest request,String type,String studentId){
        JSONObject object = new JSONObject();
        JSONObject data = new JSONObject();
        Criteria criteria = new Criteria();
        Query query = null;
        if(type.equals("teacher")){
            query = new Query(criteria.and("teacherId")
                    .is(TokenUtils.getTeacherId(request)).and("type").is(1))
                    .with(new Sort(Sort.Direction.DESC,"replyTime"));
        }
        if(type.equals("parent")){
            query = new Query(criteria.and("studentId")
                    .is(studentId).and("type").is(1))
                    .with(new Sort(Sort.Direction.DESC,"replyTime"));
        }
        List<Chitchat> chitchats =  mongoTemplate.find(query,Chitchat.class,"Chitchat");
        if(chitchats.size()>0){
            data.put("status",true);
            data.put("data",chitchats);
            object.put("status",true);
            object.put("data",data);
            return data;
        }
        data.put("status",false);
        data.put("msg","暂时没有老师留言");
        object.put("status",true);
        object.put("data",data);
        return object;
    }

    /**
     *
     * @param documentId 文档id
     * @param type 类型
     * @return
     */
    @PostMapping(value = "/queryMessageDetail")
    @ApiOperation(value = "查看某条消息的详细信息")
    public JSONObject queryMessageDetail(String documentId,String type){
        //返回封装
        JSONObject object = new JSONObject();
        JSONObject data = new JSONObject();
        Update update =null;
        //点击以后首先将标题的已读状态变更为已读
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(documentId));
        if(type.equals("teacher")){
            update =  Update.update("teacherStatus", true);

        }
        if(type.equals("parent")){
            update = Update.update("parentStatus", true);
        }

        UpdateResult upsert = mongoTemplate.upsert(query, update, "Chitchat");
        upsert.getModifiedCount();
        //接着再获取消息
        Criteria criteria = new Criteria();
        List<Chitchat> chitchat =  mongoTemplate.find(query,Chitchat.class,"Chitchat");
        Query query1 = new Query(criteria.and("pid").is(documentId))
                .with(new Sort(Sort.Direction.ASC,"addTime"));
        List<Chitchat> chitchats =  mongoTemplate.find(query1,Chitchat.class,"Chitchat");

        //组合
        chitchat.addAll(chitchats);
        data.put("status",true);
        data.put("data",chitchat);
        object.put("status",true);
        object.put("data",data);
        return object;

    }

    /**
     */
    @PostMapping(value = "/sendReply")
    @ApiOperation(value = "发送回复")
    public JSONObject sendReply(ReplyVo replyVo){
        return  chitchatService.sendReply(replyVo.getReplyContent(),replyVo.getTeacherName(),
                replyVo.getParentName(),replyVo.getTeacherId(),replyVo.getDocumentId(),replyVo.getType(),replyVo.getStudentId(),replyVo.getParentId());
    }

    @PostMapping(value = "/unreadMessage")
    @ApiOperation(value = "未读提示信号量")
    public synchronized  JSONObject unreadMessage(HttpServletRequest request,String type){
        //获取Id
        String id ;
        String stuId;
        Criteria criteria = new Criteria();
        Query query ;
        List<Chitchat> chitchat;
        boolean isStatus =false;
        //返回封装
        JSONObject object = new JSONObject();
        JSONObject data = new JSONObject();
        if(type.equals("teacher")){
            id = TokenUtils.getTeacherId(request);
            query = new Query(criteria.and("teacherId").is(id).and("type").is(1));
            chitchat = mongoTemplate.find(query,Chitchat.class,"Chitchat");
            for(Chitchat c :chitchat){
                if(!c.isTeacherStatus()){
                    isStatus =true ;
                    break;
                }
            }
            data.put("status",true);
            data.put("isUnreadMessage",isStatus);
            object.put("status",true);
            object.put("data",data);
            return object;

        }
        if(type.equals("parent")){
            id = TokenUtils.getParentId(request);
            List<Student> students = userMapper.getStudents(id);
            List<String> list = new ArrayList<>();
            for (Student s:students) {
                list.add(s.getId());
            }
                query = new Query(criteria.and("studentId").in(list).and("type").is(1));
                chitchat = mongoTemplate.find(query,Chitchat.class,"Chitchat");
                for(Chitchat c :chitchat){
                    if(!c.isParentStatus()){
                        isStatus =true ;
                        break;
                    }
                }
                System.gc();


            data.put("status",true);
            data.put("isUnreadMessage",isStatus);
            object.put("status",true);
            object.put("data",data);
            return object;
        }
        data.put("status",false);
        data.put("msg","不能获取到状态");
        object.put("status",true);
        object.put("data",data);
        return object;
    }

    /**
     *
     * @param documentId 文档id
     * @return
     */
    @PostMapping(value = "/removeMessage")
    @ApiOperation(value = "删除目标消息")
    public JSONObject removeMessage(String documentId){
        JSONObject object = new JSONObject();
        JSONObject data = new JSONObject();
        Criteria criteria = new Criteria();
        Query query = new Query(criteria.and("_id").is(documentId));
         DeleteResult deleteResult =  mongoTemplate.remove(query,"Chitchat");
        long removeOneTitle =  deleteResult.getDeletedCount();
         query = new Query(Criteria.where("pid").is(documentId));
        DeleteResult deleteResults =  mongoTemplate.remove(query,"Chitchat");
        long removeTwoTitle =  deleteResults.getDeletedCount();
        if(removeOneTitle>0 && removeTwoTitle>0){
            data.put("status",true);
            data.put("msg","删除成功");
            object.put("status",true);
            object.put("data",data);
            return object;
        }
        data.put("status",false);
        data.put("msg","删除失败");
        object.put("status",true);
        object.put("data",data);
        return object;

    }

    @PostMapping(value = "/getTeacherByClassId")
    @ApiOperation(value = "通过班级ID获取教师")
    @ResponseBody
    public Map<String,Object> getTeacherByClassId(String classId){
        Map<String,Object> map = chitchatService.getTeacherByClassId(classId);



        return map;
    }

}
